package com.cyt.work.question.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.work.question.dao.QuestionScoreDao;
import com.cyt.work.question.model.dto.QuestionUserDto;
import com.cyt.work.question.model.po.Question;
import com.cyt.work.question.model.po.QuestionScore;
import com.cyt.work.question.model.po.QuestionSubject;
import com.cyt.work.question.model.po.QuestionUser;
import com.cyt.work.question.model.vo.QuestionScoreVo;
import com.cyt.work.question.service.IQuestionScoreService;
import com.cyt.work.question.service.IQuestionService;
import com.cyt.work.question.service.IQuestionSubjectService;
import com.cyt.work.question.service.IQuestionUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuestionScoreServiceImpl extends BaseServiceImpl<QuestionScore> implements IQuestionScoreService {

    private static Logger logger = LoggerFactory.getLogger(QuestionScoreServiceImpl.class);

    @Autowired
    private IQuestionUserService questionUserService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuestionSubjectService questionSubjectService;
    @Autowired
    private QuestionScoreDao questionScoreDao;
    @Autowired
    public void setBaseDao(QuestionScoreDao questionScoreDao) {
        this.baseDao = questionScoreDao;
    }

    @Override
    public ReturnResult page(QuestionScoreVo questionScoreVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        Example example = new Example(QuestionScore.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(questionScoreVo.getApplyId())) {
            criteria.andEqualTo("applyId", questionScoreVo.getApplyId());
        }
        if (StringUtils.isNotEmpty(questionScoreVo.getQuestionId())) {
            criteria.andEqualTo("questionId", questionScoreVo.getQuestionId());
        }
        if (StringUtils.isNotEmpty(questionScoreVo.getSubjectId())) {
            criteria.andEqualTo("subjectId", questionScoreVo.getSubjectId());
        }
        List<QuestionScore> list = questionScoreDao.selectByExample(example);
        PageInfo<QuestionScore> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnResult saveQuestionScore(String userId, String scoreJson) {
        JSONObject jsonObject = JSONObject.parseObject(scoreJson);
        String questionId = jsonObject.getString("tableId");
        Question question = questionService.selectByPrimaryKey(questionId);
        if (question == null) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        // 是否是对象问卷，如果是，需要修改状态为已答卷
        if (StringUtils.equals(question.getType(), BaseConstant.QUESTION_TYPE_OBJECT)) {
            questionUserService.updateStatus(questionId, userId);
        } else {
            // 如果是扫码问卷，先查询是否已提交，如果未提交插入
            QuestionUser questionUserSearch = new QuestionUser();
            questionUserSearch.setQuestionId(questionId);
            questionUserSearch.setUserId(userId);
            List<QuestionUser> questionUserList = questionUserService.select(questionUserSearch);
            if (questionUserList == null || questionUserList.size() == 0) {
                // 插入新数据
                QuestionUser questionUser = new QuestionUser();
                questionUser.setId(BaseUtil.uId());
                questionUser.setApplyId(question.getApplyId());
                questionUser.setUserId(userId);
                questionUser.setStatus(BaseConstant.QUESTION_USER_STATUS_YES_SUBMIT);
                questionUser.setQuestionId(questionId);
                questionUser.setCreateTime(DateUtil.date());
                questionUserService.insert(questionUser);
            }
        }
        String subject = jsonObject.getString("subject");
        JSONArray subjectArray = JSONArray.parseArray(subject);
        List<QuestionScore> scoreList = new ArrayList<>();
        for (Object object : subjectArray.toArray()) {
            JSONObject subjectObj = (JSONObject)object;
            String applyId = (String) subjectObj.get("applyId");
            // 题目主键
            String subjectId = (String) subjectObj.get("subjectId");
            // 题目类型
            String type = (String) subjectObj.get("type");
            // 题目答案（选择题id，多选题用,区分开）
            String selectId = (String) subjectObj.get("selectId");
            // 得分
            String score = (String) subjectObj.get("score");
            QuestionSubject questionnaireSubject = questionSubjectService.selectByPrimaryKey(subjectId);
            if (questionnaireSubject == null) {
                break;
            }
            // 设置得分
            QuestionScore questionScore = new QuestionScore();
            questionScore.setId(BaseUtil.uId());
            questionScore.setApplyId(applyId);
            questionScore.setQuestionId(questionId);
            questionScore.setUserId(userId);
            questionScore.setSubjectType(type);
            questionScore.setSubjectId(questionnaireSubject.getId());
            questionScore.setScoreList(selectId);
            questionScore.setScore(Double.valueOf(score));
            questionScore.setCreateTime(new Date());
            scoreList.add(questionScore);
        }
        // 先删除
        Example example = new Example(QuestionScore.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(questionId)) {
            criteria.andEqualTo("questionId", questionId);
        }
        if (StringUtils.isNotBlank(userId)) {
            criteria.andEqualTo("userId", userId);
        }
        questionScoreDao.deleteByExample(example);
        logger.info("先删除：" + userId + "问卷，然后保存");
        // 保存
        questionScoreDao.insertScoreList(scoreList);
        logger.info("保存：" + userId + "问卷...");
        return new ReturnResult();
    }

    @Override
    public long selectCountGroupByUser(QuestionScore questionScore) {
        return questionScoreDao.selectCountGroupByUser(questionScore);
    }

    @Override
    public List<QuestionUserDto> selectUserList(String questionId) {
        List<QuestionUserDto> questionUserList = questionScoreDao.selectUserList(questionId);
        if (questionUserList != null && questionUserList.size() > 0) {
            for (QuestionUserDto questionUserDto : questionUserList) {
                if (StringUtils.isNotEmpty(questionUserDto.getUserName())) {
                    questionUserDto.setUserName(BaseUtil.decodeBase64(questionUserDto.getUserName()));
                }
            }
        }
        return questionUserList;
    }

    @Override
    public List<QuestionScore> accept(QuestionScoreVo questionScoreVo) {
        Example example = new Example(QuestionScore.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(questionScoreVo.getApplyId())) {
            criteria.andEqualTo("applyId", questionScoreVo.getApplyId());
        }
        if (StringUtils.isNotEmpty(questionScoreVo.getQuestionId())) {
            criteria.andEqualTo("questionId", questionScoreVo.getQuestionId());
        }
        if (StringUtils.isNotEmpty(questionScoreVo.getSubjectId())) {
            criteria.andEqualTo("subjectId", questionScoreVo.getSubjectId());
        }
        return questionScoreDao.selectByExample(example);
    }
}
